<template>
    <div class="user-list">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-input
                v-model="searchQuery"
                placeholder="搜索用户名/邮箱"
                style="width: 200px"
                @keyup.enter="handleSearch"
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAdd">新增用户</el-button>
        </div>

        <!-- 用户表格 -->
        <el-table :data="userList" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="用户信息" min-width="200">
                <template #default="{ row }">
                    <div class="user-info">
                        <el-avatar :size="40" :src="row.avatar_url">
                            {{ row.username.charAt(0).toUpperCase() }}
                        </el-avatar>
                        <div class="user-details">
                            <div class="username">{{ row.username }}</div>
                            <div class="email">{{ row.email }}</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="角色" min-width="150">
                <template #default="{ row }">
                    <el-tag 
                        v-for="role in row.roles" 
                        :key="role.id"
                        :type="getRoleTagType(role.code)"
                        class="role-tag"
                        size="small"
                    >
                        {{ role.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="is_active" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.is_active ? 'success' : 'info'">
                        {{ row.is_active ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
                <template #default="{ row }">
                    {{ formatDateTime(row.created_at) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button 
                        size="small" 
                        type="primary"
                        @click="handleAssignRoles(scope.row)"
                    >分配角色</el-button>
                    <el-button
                        size="small"
                        :type="scope.row.is_active ? 'warning' : 'success'"
                        @click="handleToggleStatus(scope.row)"
                    >
                        {{ scope.row.is_active ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />

        <!-- 添加/编辑对话框 -->
        <el-dialog
            :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
            v-model="dialogVisible"
            width="500px"
        >
            <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
                    <el-input v-model="userForm.password" type="password" show-password />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="userForm.is_active" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>

        <!-- 分配角色对话框 -->
        <el-dialog
            title="分配角色"
            v-model="roleDialogVisible"
            width="500px"
        >
            <div class="role-assign-container">
                <el-checkbox-group v-model="selectedRoles">
                    <div class="role-list">
                        <el-checkbox 
                            v-for="role in allRoles" 
                            :key="role.id" 
                            :label="role.id"
                            class="role-item"
                        >
                            <div class="role-info">
                                <span class="role-name">{{ role.name }}</span>
                                <el-tag 
                                    size="small" 
                                    :type="getRoleTagType(role.code)"
                                >{{ role.code }}</el-tag>
                                <div class="role-desc">{{ role.description || '暂无描述' }}</div>
                            </div>
                        </el-checkbox>
                    </div>
                </el-checkbox-group>
            </div>
            <template #footer>
                <el-button @click="roleDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import http from '@/utils/http'

// 数据
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)

const userForm = ref({
    username: '',
    email: '',
    password: '',
    is_active: true,
    role_ids: []

})

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}




// 修改获取用户列表方法为使用模拟数据
const getUserList = async () => {
  try {
    // 模拟API请求延迟
      const data = await http.get('/users', {
          params: {
              page: currentPage.value,
              limit: pageSize.value
          }
      })
      userList.value = data
    
    // 模拟搜索过滤
      let filteredUsers = [...userList.value]
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      filteredUsers = filteredUsers.filter(user => 
        user.username.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query)
      )
    }
    
    // 模拟分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    userList.value = filteredUsers.slice(start, end)
    total.value = filteredUsers.length
    
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getUserList()
}

// 新增用户
const handleAdd = () => {
    dialogType.value = 'add'
    userForm.value = {
        username: '',
        email: '',
        password: '',
        is_active: true,
        role_ids: []
    }
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
    currentUserId.value = row.id
    dialogType.value = 'edit'
    userForm.value = { ...row }
    dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该用户吗？', '提示', {
        type: 'warning'
    })
        .then(async () => {
            try {
                // 这里替换成实际的API请求
                await fetch(`/api/users/${row.id}`, {
                    method: 'DELETE'
                })
                ElMessage.success('删除成功')
                getUserList()
            } catch (error) {
                console.error('删除用户失败:', error)
                ElMessage.error('删除用户失败')
            }
        })
        .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        
        
        if (dialogType.value === 'add') {
          // 模拟添加用户
            await http.post('/users', userForm.value)
          ElMessage.success('添加成功')
        } else {
          // 模拟编辑用户
            await http.put(`/users/${currentUserId.value}`, {
                "username": userForm.value.username,
                "email": userForm.value.email,
                "is_active": userForm.value.is_active,
            })
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getUserList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 页码改变
const handlePageChange = (page) => {
    currentPage.value = page
    getUserList()
}

// 页大小改变
const handleSizeChange = (size) => {
    pageSize.value = size
    getUserList()
}

// 角色分配相关
const roleDialogVisible = ref(false)
const allRoles = ref([])
const selectedRoles = ref([])
const currentUserId = ref(null)

// 修改获取角色列表方法为使用模拟数据
const getAllRoles = async () => {
  try {
      const data = await http.get('/roles')
      allRoles.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 修改分配角色相关的方法
const handleAssignRoles = async (row) => {
    currentUserId.value = row.id
    selectedRoles.value = row.roles.map(role => role.id)
    
    // 如果还没有获取角色列表，先获取
    if (allRoles.value.length === 0) {
        await getAllRoles()
    }
    
    roleDialogVisible.value = true
}

// 提交角色分配
const handleRoleSubmit = async () => {
    try {
        await http.put(`/users/${currentUserId.value}/roles`, {
            role_ids: selectedRoles.value
        })
        
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
        getUserList() // 刷新用户列表
    } catch (error) {
        console.error('角色分配失败:', error)
        ElMessage.error('角色分配失败')
    }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const user = mockUsers.find(u => u.id === row.id)
    if (user) {
      user.is_active = !user.is_active
      ElMessage.success(`${user.is_active ? '启用' : '禁用'}成功`)
      getUserList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
    return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// 获取角色标签类型
const getRoleTagType = (code) => {
  switch (code) {
    case 'admin':
      return 'danger'
    case 'operator':
      return 'warning'
    case 'user':
      return 'info'
    default:
      return 'info'  // 默认返回 'info' 而不是空字符串
  }
}

// 初始化
onMounted(() => {
    getUserList()
    getAllRoles()
})
</script>

<style scoped>
.user-list {
    padding: 20px;
}
.search-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}
.user-info {
    display: flex;
    align-items: center;
    gap: 10px;
}
.user-details {
    display: flex;
    flex-direction: column;
}
.username {
    font-weight: bold;
}
.email {
    font-size: 12px;
    color: #999;
}
.role-tag {
    margin-right: 5px;
}
.el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
}

/* 添加新的样式 */
.role-assign-container {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px;
}

.role-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.role-item {
    width: 100%;
    padding: 10px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.role-item:hover {
    background-color: var(--el-fill-color-light);
}

.role-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: 8px;
}

.role-name {
    font-weight: bold;
    min-width: 80px;
}

.role-desc {
    color: var(--el-text-color-secondary);
    font-size: 12px;
    margin-left: 8px;
}

:deep(.el-checkbox__input) {
    align-self: flex-start;
    margin-top: 2px;
}

:deep(.el-checkbox__label) {
    white-space: normal;
}
</style>
``` 